package com.jdbcsimple.datasource;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * abstract base class for JdbcSimple's {@link javax.sql.DataSource} implementations
 * that use JDBC {@link java.sql.Driver} to get {@link java.sql.Connection}
 * @author Leonard Lan
 * @since 09.04.2013
 */
public abstract class AbstractDriverBasedDataSource extends AbstractDataSource{
	private String url;
	private String username;
	private String password;
	private Properties connectionProperties;

	@Override
	public Connection getConnection() throws SQLException {
		return getConnectionFromDriver(getUsername(),getPassword());
	}

	@Override
	public Connection getConnection(String username, String password)
			throws SQLException {
		return getConnectionFromDriver(username,password);
	}

	protected Connection getConnectionFromDriver(String username, String password) throws SQLException {
		Properties props = new Properties(getConnectionProperties());
		if (username != null) {
			props.setProperty("user", username);
		}
		if (password != null) {
			props.setProperty("password", password);
		}
		return getConnectionFromDriver(props);
	}
	
	protected abstract Connection getConnectionFromDriver(Properties properties) throws SQLException;
	
	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		if((CharSequence)url == null || ((CharSequence)url).length() < 0){
			throw new IllegalArgumentException("Property 'url' must not be empty");
		}
		this.url = url;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public Properties getConnectionProperties() {
		return connectionProperties;
	}

	public void setConnectionProperties(Properties connectionProperties) {
		this.connectionProperties = connectionProperties;
	}
}
